package com.alinesno.cloud.common.web.base.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alinesno.cloud.common.web.base.constants.WebConstants;
import com.alinesno.cloud.common.web.base.utils.CookieUtils;

/**
 * 页面拦截
 * 
 * @author LuoAnDong
 * @since 2018年8月24日 下午10:42:25
 */
//@Component
public class PageSessionInterceptor implements HandlerInterceptor {

	private static final Logger log = LoggerFactory.getLogger(ManagerSessionInterceptor.class);
	
	// 标示符：表示当前用户未登录(可根据自己项目需要改为json样式)
//	ResponseBean<String> NO_LOGIN = ResultGenerator.genFailMessage("您还未登录") ;
	private static final String NO_LOGIN_URL = "/wx/auth/path" ;

	@Autowired
	private CookieUtils cookieUtils ; 

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		log.debug("过滤微信页面权限.");
		
		HttpSession session = request.getSession();
		String fromWhere = cookieUtils.fullUrl(request);

		if (session != null && session.getAttribute(WebConstants.CURRENT_USER) != null) { // session中包含user对象,则是登录状态
			return true ; 
		} else {
			String requestType = request.getHeader("X-Requested-With");
			
			if(session != null) {
				session.setAttribute(WebConstants.FROM_WHERE, fromWhere);
				if (requestType != null && "XMLHttpRequest".equals(requestType)) { // 判断是否是ajax请求
					response.getWriter().write("");
					return false ; 
				} else {
					response.sendRedirect(request.getContextPath() + NO_LOGIN_URL); // 重定向到登录页(需要在static文件夹下建立此html文件)
					return false ; 
				}
			}
			
			response.sendRedirect(request.getContextPath() + NO_LOGIN_URL); // 重定向到登录页(需要在static文件夹下建立此html文件)
			return false ; 
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
}
